package cn.cxy.demo

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    var myBinder: MyService.MyBinder? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initListeners()
    }

    private fun initListeners() {
        //绑定Service
        bindBtn.setOnClickListener {
            val intent = Intent(this, MyService::class.java)
            bindService(intent, serviceConnection, BIND_AUTO_CREATE)
        }

        //解绑Service
        unBindBtn.setOnClickListener { unbindService(serviceConnection) }

        //通过绑定关系和Service通信，调用Service里的方法
        studyBtn.setOnClickListener { myBinder?.study() }
        progressBtn.setOnClickListener { myBinder?.getProgress() }
    }

    /**
     * 创建Service绑定连接
     */
    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, binder: IBinder) {
            myBinder = binder as MyService.MyBinder
        }

        override fun onServiceDisconnected(name: ComponentName) {}
    }
}